package com.feeyo.prophet.config;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.AbstractMatcherFilter;
import ch.qos.logback.core.spi.FilterReply;

/**
 * 日志记录filter
 *
 * @author sk
 * @since 6/19/23 10:26
 */
public class LogBackLevelFilter extends AbstractMatcherFilter<ILoggingEvent> {

    private static final String CBB_LOG_PRE = "FEEYO_CBB_LOG";

    private Level level;

    private boolean normal = true;

    private boolean apilog = false;

    public LogBackLevelFilter() {
    }

    @Override
    public FilterReply decide(ILoggingEvent event) {
        String loggerName = event.getLoggerName();
        if (loggerName.startsWith(CBB_LOG_PRE)) {
            if (!apilog) {
                return this.onMismatch;
            }
        } else if (!normal) {
            return this.onMismatch;
        }

        if (!this.isStarted()) {
            return FilterReply.NEUTRAL;
        } else {
            return event.getLevel().equals(this.level) ? this.onMatch : this.onMismatch;
        }
    }

    public void setLevel(Level level) {
        this.level = level;
    }

    public void setNormal(boolean normal) {
        this.normal = normal;
    }

    public void setApilog(boolean apilog) {
        this.apilog = apilog;
    }

    @Override
    public void start() {
        if (this.level != null) {
            super.start();
        }

    }
}
